<template>
	<div class="session">
		<van-nav-bar title="聊天机器人"/>
		<div>
			<div v-if="sessionList.length == 0" id="ai_assistance"  class="padding">
				<h3>AI小助手</h3>
				<p>还没创建会话，快来试试吧！</p>
				<ul>
					<li v-for="item in list" @click="createSession(item)">{{item}}</li>
				</ul>
			</div>
			<div v-else>
				<van-swipe-cell v-for="(session, index) in sessionList" :key="index">
					<div class="sessionRecode" @click="this.$router.push({path: '/chat/' + session.id})">
						<div><img src="../../assets/image/icon/chatGPT.png" width="50px" height="50px"></div>
						<div>
							<p class="question ellipsis">{{session.lastQuestion == null ? "您还没有开始对话哦~" : session.lastQuestion}}</p>
							<p class="time">{{session.createTime}}</p>
						</div>
						<div style="font-size: 13px; margin-right: 5px;">{{session.count}}条记录</div>
					</div>
				  <template #right>
				    <van-button square type="danger" text="删除" style="height: 100%; margin-top: 0px;" @click="deleteSession(session.id)"/>
				  </template>
				</van-swipe-cell>
			</div>
		</div>
		<footer>
			<van-button type="success" round @click="createSession(null)">
				<van-icon name="add-o" style="margin-right: 1px; vertical-align: middle;" size="20"/> <span style="vertical-align: middle;">创建新的会话</span>
			</van-button>
		</footer>
	</div>
</template>

<script>
	import { showSuccessToast, showFailToast, showConfirmDialog } from 'vant';
	export default{
		data(){
			return{
				sessionList:[],
				list:['长沙有哪些特产？', '给帮我做一份旅行规划吧。', '最近长沙有哪些电影上映吗？', '请帮我做一份辣椒炒肉的菜谱。', '我想考清华需要付出什么样的努力？'],
			}
		},
		methods:{
			createSession(content){
				this.$http.post(this.$api.CREATE_AI_SESSION).then(result => {
					if(result.code == 200){
						if(content == null) this.$router.push({path: '/chat/' + result.body}); 
						else this.$router.push({path: '/chat/' + result.body, query:{q: content}});
					}else{
						showFailToast("会话创建失败，请稍后重试。");
					}
				});
			},
			getSessionList(){
				this.$http.get(this.$api.AI_SESSION_LIST).then(result => {
					if(result.code == 200) this.sessionList = result.body;
				})
			},
			deleteSession(sessionId){
				showConfirmDialog({message: '是否删除当前会话？'}).then(() => {
				    this.$http.delete(this.$api.DELETE_SESSION, {
						params:{
							id: sessionId
						}
					}).then(result => {
						if(result.code == 200){
							this.getSessionList();
							showSuccessToast("删除成功"); return;
						}else{
							showFailToast("删除失败");
						}
					})
				})
			}
		},
		created() {
			this.getSessionList();
		}
	}
</script>

<style scoped>
	@import "../../assets/css/session.css";
</style>